package com.smcdd.cdb.dbo.cdb_dbo.ui.base;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.service.receiver.NetworkConnectChangedReceiver;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.AwaitDialog;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.WifiDialog;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity<V, T extends BasePresenter<V>> extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    protected T mPresenter;
    private static final int RC_CAMERA_PERM = 123;
    private static final int RC_LOCATION_CONTACTS_PERM = 124;
    private static final int RC_SETTINGS_SCREEN = 125;
    private static final int READ_WRITE = 126;
    private static final int All = 128;
    private static final int SUCCESS = 1000;
    private boolean flag = false;
    private static final String TAG = BaseActivity.class.getSimpleName();
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == SUCCESS) {
                flag = true;
            }
        }
    };
    private NetworkConnectChangedReceiver receiver;
    private WifiDialog selfDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();

        //判断是否使用MVP模式
        mPresenter = createPresenter();
        if (mPresenter != null) {
            mPresenter.attachView((V) this);//因为之后所有的子类都要实现对应的View接口
        }

        //子类不再需要设置布局ID，也不再需要使用ButterKnife.bind()
        setContentView(provideContentViewId());

        IntentFilter filter = new IntentFilter();
        receiver = new NetworkConnectChangedReceiver();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);

        receiver.setItemClickListenter(name -> {
            if (name != null && name.contains("ChongDianDian")) {
                dialog("当前所连接的是设备的wiif\r\n"+name+"\r\n点击确认去往wifi配置界面");
            }
        });

        initView();
        initData();
        initListener();
    }

    public void dialog(String a) {
        selfDialog = new WifiDialog(this);
        selfDialog.setMessage(a);
        selfDialog.show();
        selfDialog.setItemClickListenter(() -> {
            selfDialog.dismiss();
        });
        selfDialog.setItemClickListentertwo(() -> {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse("http://192.168.4.1/wifi_set.html");
            intent.setData(content_url);
            startActivity(intent);
            selfDialog.dismiss();
        });
    }


//    protected void dialog(String name) {
//
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setMessage("当前所连接的是设备的wiif\r\n"+name+"\r\n点击确认去往wifi配置界面");
//        builder.setTitle("提示");
//        builder.setPositiveButton("确认",(dialog, which) -> {
//            Intent intent = new Intent();
//            intent.setAction("android.intent.action.VIEW");
//            Uri content_url = Uri.parse("http://192.168.4.1/wifi_set.html");
//            intent.setData(content_url);
//            startActivity(intent);
//            dialog.dismiss();
//        });
//            builder.setNegativeButton("取消", (dialog, which) -> {
//                dialog.dismiss();
//            });
//        builder.create().show();
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        initUnData();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        unregisterReceiver(receiver);
    }

    public void initUnData() {

    }

    //在setContentView()调用之前调用，可以设置WindowFeature(如：this.requestWindowFeature(Window.FEATURE_NO_TITLE);)
    public void init() {
    }

    public void initView() {
    }

    public void initData() {
    }

    public void initListener() {
    }

    //用于创建Presenter和判断是否使用MVP模式(由子类实现)
    protected abstract T createPresenter();

    //得到当前界面的布局文件id(由子类实现)
    protected abstract int provideContentViewId();



    public void jumpToActivity(Intent intent) {
        startActivity(intent);
    }

    public void jumpToActivity(Class activity) {
        Intent intent = new Intent(this, activity);
        startActivity(intent);
    }


    public void jumpToActivityAndClearTask(Class activity) {
        Intent intent = new Intent(this, activity);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    public void jumpToActivityAndClearTop(Class activity) {
        Intent intent = new Intent(this, activity);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public boolean camePermission(){
//        if (checkInitPermission()) {
//            return true;
//        }else {
//            return cameraTask();
//        }
//
        return checkInitPermission() ? true : cameraTask();

    }

    public boolean locationPermission(){
//        if (!checkInitPermission()) {
//            locationAndContactsTask();
//        }
        return checkInitPermission() ? true : locationAndContactsTask();
    }

    public boolean SdPermission(){

        return checkInitPermission() ? true : SD();
    }


    public boolean ListPermission(){
        return all();
    }





    public boolean checkInitPermission(){
        // SDK 小于23默认已经授权
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }else {
            return false;
        }

    }

    //所有权限
    @AfterPermissionGranted(All)
    public boolean all() {
        String[] perms = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE,
                Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Have permissions, do the thing!
            // Toast.makeText(this, "TODO: Location and Contacts things", Toast.LENGTH_LONG).show();
            return true;
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                    All, perms);
            return false;
        }
    }



    //相机权限
    @AfterPermissionGranted(RC_CAMERA_PERM)
    public boolean cameraTask() { //RECORD_AUDIO
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
           // Toast.makeText(this, "TODO: Camera things", Toast.LENGTH_LONG).show();
            return true;
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_camera),
                    RC_CAMERA_PERM, Manifest.permission.CAMERA);
            return false;
        }
    }

    //SD卡权限
    @AfterPermissionGranted(READ_WRITE)
    public boolean SD() {
        String[] perms = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Have permissions, do the thing!
            // Toast.makeText(this, "TODO: Location and Contacts things", Toast.LENGTH_LONG).show();
            return true;
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                    READ_WRITE, perms);
            return false;
        }
    }



    //Location权限
    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    public boolean locationAndContactsTask() {
        String[] perms = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ,Manifest.permission.CALL_PHONE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Have permissions, do the thing!
           // Toast.makeText(this, "TODO: Location and Contacts things", Toast.LENGTH_LONG).show();
            return true;
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                    RC_LOCATION_CONTACTS_PERM, perms);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
       // handler.sendMessage(handler.obtainMessage(SUCCESS));
        Log.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.rationale_ask_again))
                    .setTitle(getString(R.string.title_settings_dialog))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null /* click listener */)
                    .setRequestCode(RC_SETTINGS_SCREEN)
                    .build()
                    .show();
        }
    }


}
